<template>
	<view class="container">
		<!-- 头部导航 -->
		<!-- <view class="header">
			<view class="back-btn" @click="goBack">
				<image src="/static/icons/icon-Get-into@3.png" class="back-icon"></image>
			</view>
			<text class="page-title">填写市运营信息</text>
		</view> -->

		<!-- 表单内容 -->
		<view class="form-wrapper">
			<!-- 申请地区 -->
			<view class="form-item">
				<text class="required">*</text>
				<text class="label">申请市运营地区:</text>
				<input v-model="formData.regionText" placeholder="请选择运营地区" readonly @click="showRegionPicker"
					class="input-field" />
			</view>

			<!-- 姓名 -->
			<view class="form-item">
				<text class="required">*</text>
				<text class="label">姓名:</text>
				<input v-model="formData.realname" disabled class="input-field disabled" />
			</view>

			<!-- 身份证号 -->
			<view class="form-item">
				<text class="required">*</text>
				<text class="label">身份证号:</text>
				<input v-model="formData.id_number" disabled class="input-field disabled" />
			</view>

			<!-- 手持身份证拍照 -->
			<view class="photo-section">
				<view class="section-title">
					<text class="required">*</text>
					<text>手持身份证拍照</text>
				</view>
				<view class="photo-row">
					<view class="photo-item" @click="chooseImage('idfront')">
						<image :src="formData.idfromt || serverAddress+'/img/icon-sfz(zheng)@2x.png'"
							class="photo-img-idcard"></image>
						<text class="photo-label">身份证正面</text>
					</view>
					<view class="photo-item" @click="chooseImage('idback')">
						<image :src="formData.idback || serverAddress+'/img/icon-sfz(fan)@2x.png'"
							class="photo-img-idcard"></image>
						<text class="photo-label">身份证反面</text>
					</view>
				</view>
			</view>

			<!-- 办公场地照片 -->
			<view class="photo-section">
				<view class="section-title">
					<text class="required">*</text>
					<text>办公场地照片</text>
				</view>
				<view class="photo-row">
					<view class="photo-item" @click="chooseImage('workScene')">
						<image :src="formData.workSpot || serverAddress+'/img/icon-photo1（tianxieshangjia）@2x.png'"
							class="photo-img work-photo"></image>
					</view>
				</view>
			</view>

			<!-- 团队照片 -->
			<view class="photo-section">
				<view class="section-title">
					<text class="required">*</text>
					<text>团队照片</text>
				</view>
				<view class="photo-row">
					<view class="photo-item" @click="chooseImage('teamStaff')">
						<image :src="formData.teamP || serverAddress+'/img/icon-photo1（tianxieshangjia）@2x.png'"
							class="photo-img work-photo"></image>
					</view>
				</view>
			</view>

			<!-- 本人签字 -->
			<view class="photo-section">
				<view class="section-title">
					<text class="required">*</text>
					<text>本人签字</text>
				</view>
				<view class="photo-row">
					<view class="photo-item" @click="showSignature">
						<image :src="formData.nameP || serverAddress+'/img/icon-default-qm.png'"
							class="signature-img"></image>
					</view>
				</view>
			</view>

			<!-- 申请日期 -->
			<view class="info-item">
				<text>申请日期：</text>
				<text class="date-text">{{ applyDate }}</text>
			</view>

			<!-- 协议 -->
			<view class="agreement-item" @click="toggleAgreement">
				<!-- <text :class="['agreement-text', { 'unread': !isAgreed }]"> -->

				<image :src="serverAddress + (isAgreed ? 'img/login/icon-dui.png' : 'img/check.png')"
					class="check-icon"></image>

				<text>我已阅读并同意</text>
				<text class="agreement-link" @click.stop="viewAgreement">《市优享优品平台运营协议》</text>
				<!-- </text> -->
			</view>

			<!-- 提醒 -->
			<text class="tip-text">提醒：以上录入信息优享优品平台会进行核实</text>

			<!-- 提交按钮 -->
			<button class="submit-btn" @click="submitForm">提交</button>
		</view>

		<!-- 地区选择器 -->
		<!-- <picker-view v-if="showRegionModal" :value="regionPickerValue" @change="onRegionChange" class="region-picker">
			<picker-view-column>
				<view v-for="(province, index) in regionData" :key="index">
					{{ province.region_name }}
				</view>
			</picker-view-column>
			<picker-view-column>
				<view v-for="(city, index) in currentCities" :key="index">
					{{ city.region_name }}
				</view>
			</picker-view-column>
			<picker-view-column>
				<view v-for="(district, index) in currentDistricts" :key="index">
					{{ district.region_name }}
				</view>
			</picker-view-column>
		</picker-view> -->
		
		<u-picker 
			:show="showRegionModal" 
		    :columns="pickerColumns"
		    @confirm="confirmRegion"
		    @cancel="cancelRegion"
			keyName="label"
		    title="选择地区"
		></u-picker>

		<!-- 电子签名弹窗 -->
		<view v-if="showSignatureModal" class="signature-modal">
			<view class="signature-header">
				<view class="back-btn" @click="closeSignature">
					<image src="/static/icon-Get-into@3.png" class="back-icon"></image>
				</view>
				<text class="page-title">电子签名</text>
			</view>
			<canvas canvas-id="signatureCanvas" class="signature-canvas" @touchstart="touchStart" @touchmove="touchMove"
				@touchend="touchEnd"></canvas>
			<view class="signature-actions">
				<button @click="clearSignature" class="action-btn">清除</button>
				<button @click="saveSignature" class="action-btn primary">完成</button>
			</view>
		</view>

		<!-- 成功提示弹窗 -->
		<view v-if="showSuccessModal" class="success-modal">
			<view class="modal-content">
				<text class="success-title">您的市运营申请已提交成功，请尽快缴纳市运营权限费，并上传缴费凭证！</text>
				<view class="fee-info">
					<view class="fee-left">
						<text class="fee-label">权限费：</text>
						<text class="payment-method">银行汇款：</text>
						<text>户名：</text>
						<text>账号：</text>
						<text>开户银行：</text>
						<text>客服电话：</text>
						<text class="payment-method">扫码支付：</text>
					</view>
					<view class="fee-right">
						<text class="fee-desc">省会城市<text class="amount">25</text>万元，地级市<text
								class="amount">20</text>万，县级市<text class="amount">15</text>万，北、上、广、天津、重庆、港澳台分区<text
								class="amount">15</text>万，县<text class="amount">10</text>万</text>
						<text>北京平安优享互联网科技有限公司</text>
						<text>342872307532</text>
						<text>中国银行股份有限公司北京十里堡支行</text>
						<text>010-65776071</text>
						<view class="qr-codes">
							<image src="/static/tanchu_weixin@2x.png" class="qr-code"></image>
							<image src="/static/tanchu_zfb@2x.png" class="qr-code"></image>
						</view>
					</view>
				</view>
				<button @click="confirmSuccess" class="confirm-btn">确认</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		agentApi
	} from '@/api/index.js'
	import {
		inject
	} from 'vue'
	export default {
		data() {
			return {
				serverAddress: inject('$serverAddress', ''),
				formData: {
					region: '',
					regionText: '',
					realname: '',
					id_number: '',
					idfromt: '',
					idback: '',
					workSpot: '',
					teamP: '',
					nameP: ''
				},
				applyDate: '',
				isAgreed: false,
				showRegionModal: false,
				showSignatureModal: false,
				showSuccessModal: false,
				
				regionData: [],
				regionPickerValue: [0, 0, 0],
				currentCities: [],
				currentDistricts: [],
				
				pickerColumns: [[], [], []],
				pickerIndexes: [0, 0, 0],
				agentId: '',
				canvasContext: null,
				isDrawing: false,
				lastPoint: null
			}
		},

		onLoad(options) {
			this.agentId = options.id || ''
			this.initPage()
		},

		methods: {
			async initPage() {
				// 设置申请日期
				const date = new Date()
				this.applyDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`

				// 获取用户身份信息
				await this.getUserIdentityInfo()

				// 加载地区数据
				await this.loadRegionData()

				// 如果有ID，获取已填写的信息
				if (this.agentId) {
					await this.getAgentInfo()
				}
			},

			async getUserIdentityInfo() {
				try {
					const res = await agentApi.getIdentityInfo()
					if (res.r === 0) {
						this.formData.realname = res.data.realname || ''
						this.formData.id_number = res.data.id_number || ''
					}
				} catch (error) {
					console.error('获取身份信息失败:', error)
				}
			},

			async loadRegionData() {
				try {
					const res = await agentApi.getAllRegion()
					if (res.r === 0) {
						this.regionData = res.data.gr || []
						// if (this.regionData.length > 0) {
						// 	this.currentCities = this.regionData[0].child || []
						// 	if (this.currentCities.length > 0) {
						// 		this.currentDistricts = this.currentCities[0].child || []
						// 	}
						// }
						// 格式化数据为 u-picker 所需的格式
						                this.formatPickerData()
					}
				} catch (error) {
					console.error('获取地区数据失败:', error)
				}
			},
			
			 // 新增格式化数据的方法
			    formatPickerData() {
					
			        if (this.regionData.length > 0) {
			            // 省份列
			            this.pickerColumns[0] = this.regionData.map(province => ({
			                label: province.region_name,
			                value: province.id
			            }))
						console.log('=======regiondata=======',this.pickerColumns)
			            
			            // 城市列
			            const cities = this.regionData[0].child || []
			            this.pickerColumns[1] = cities.map(city => ({
			                label: city.region_name,
			                value: city.id
			            }))
			            
			            // 区县列
			            const districts = cities.length > 0 ? (cities[0].child || []) : []
			            this.pickerColumns[2] = districts.map(district => ({
			                label: district.region_name,
			                value: district.id
			            }))
			        }
			    },
				 // 替换显示地区选择器的方法
				    showRegionPicker() {
				        this.showRegionModal = true
				    },
				    
				    // 替换原有的 onRegionChange 方法
				    // 新增确认选择的方法
				    confirmRegion(e) {
				        const { value, indexs } = e
						console.log('=======111111111=======',value+'====',indexs)
						
				        this.pickerIndexes = indexs
				        
				        // 获取选中的省市区名称
				        const province = this.pickerColumns[0][indexs[0]]
				        const city = this.pickerColumns[1][indexs[1]]
				        const district = this.pickerColumns[2][indexs[2]]
				        
				        // 设置表单数据
				        this.formData.regionText = province.label + city.label + (district ? district.label : '')
				        this.formData.region = district ? district.value : city.value
				        
				        this.showRegionModal = false
				    },
				    
				    // 新增取消选择的方法
				    cancelRegion() {
				        this.showRegionModal = false
				    },
				    
				    // 监听省份和城市变化，动态更新下级选项
				    columnChange(e) {
				        const { columnIndex, index } = e
				        
				        if (columnIndex === 0) { // 省份变化
				            // 更新城市列
				            const cities = this.regionData[index].child || []
				            this.pickerColumns[1] = cities.map(city => ({
				                label: city.region_name,
				                value: city.id
				            }))
				            
				            // 更新区县列
				            const districts = cities.length > 0 ? (cities[0].child || []) : []
				            this.pickerColumns[2] = districts.map(district => ({
				                label: district.region_name,
				                value: district.id
				            }))
				            
				            // 重置索引
				            this.pickerIndexes = [index, 0, 0]
				        } else if (columnIndex === 1) { // 城市变化
				            // 更新区县列
				            const provinceIndex = this.pickerIndexes[0]
				            const cities = this.regionData[provinceIndex].child || []
				            const districts = cities.length > 0 ? (cities[index].child || []) : []
				            
				            this.pickerColumns[2] = districts.map(district => ({
				                label: district.region_name,
				                value: district.id
				            }))
				            
				            // 更新索引
				            this.pickerIndexes = [provinceIndex, index, 0]
				        }
				        
				        // 通知 u-picker 更新数据
				        this.$refs.uPicker && this.$refs.uPicker.updateColumns()
				    },
				

			async getAgentInfo() {
				try {
					const res = await agentApi.getAgentList({
						id: this.agentId
					})
					if (res.r === 0 && res.data.al && res.data.al.length > 0) {
						const agentInfo = res.data.al.find(item => item.id == this.agentId)
						if (agentInfo) {
							this.formData.region = agentInfo.dist_id || agentInfo.region
							// 设置图片路径
							if (agentInfo.imgs) {
								agentInfo.imgs.forEach(img => {
									switch (img.img_type) {
										case 1:
											this.formData.idfromt = img.file_path
											break
										case 2:
											this.formData.idback = img.file_path
											break
										case 3:
											this.formData.nameP = img.file_path
											break
										case 4:
											this.formData.workSpot = img.file_path
											break
										case 5:
											this.formData.teamP = img.file_path
											break
									}
								})
							}
							this.applyDate = this.formatDate(agentInfo.updated)
						}
					}
				} catch (error) {
					console.error('获取代理信息失败:', error)
				}
			},

			

			onRegionChange(e) {
				const [provinceIndex, cityIndex, districtIndex] = e.detail.value
				this.regionPickerValue = e.detail.value

				// 更新城市列表
				if (this.regionData[provinceIndex]) {
					this.currentCities = this.regionData[provinceIndex].child || []

					// 更新区县列表
					if (this.currentCities[cityIndex]) {
						this.currentDistricts = this.currentCities[cityIndex].child || []

						// 设置选中的地区
						const province = this.regionData[provinceIndex]
						const city = this.currentCities[cityIndex]
						const district = this.currentDistricts[districtIndex]

						this.formData.regionText = province.region_name + city.region_name + (district ? district
							.region_name : '')
						this.formData.region = district ? district.id : city.id
					}
				}
			},

			chooseImage(type) {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'],
					success: (res) => {
						this.uploadImage(res.tempFilePaths[0], type)
					}
				})
			},

			async uploadImage(filePath, type) {
				uni.showLoading({
					title: '上传中...'
				})

				try {
					const res = await agentApi.uploadImage({
						filePath: filePath,
						name: 'file'
					})

					if (res.r === 0) {
						switch (type) {
							case 'idfront':
								this.formData.idfromt = res.data.file_path
								break
							case 'idback':
								this.formData.idback = res.data.file_path
								break
							case 'workScene':
								this.formData.workSpot = res.data.file_path
								break
							case 'teamStaff':
								this.formData.teamP = res.data.file_path
								break
						}
					} else {
						uni.showToast({
							title: '上传失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('上传图片失败:', error)
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			showSignature() {
				this.showSignatureModal = true
				this.$nextTick(() => {
					this.canvasContext = uni.createCanvasContext('signatureCanvas', this)
					this.canvasContext.setStrokeStyle('#000000')
					this.canvasContext.setLineWidth(2)
					this.canvasContext.setLineCap('round')
				})
			},

			closeSignature() {
				this.showSignatureModal = false
			},

			touchStart(e) {
				this.isDrawing = true
				this.lastPoint = {
					x: e.touches[0].x,
					y: e.touches[0].y
				}
			},

			touchMove(e) {
				if (!this.isDrawing) return

				const currentPoint = {
					x: e.touches[0].x,
					y: e.touches[0].y
				}

				this.canvasContext.beginPath()
				this.canvasContext.moveTo(this.lastPoint.x, this.lastPoint.y)
				this.canvasContext.lineTo(currentPoint.x, currentPoint.y)
				this.canvasContext.stroke()
				this.canvasContext.draw(true)

				this.lastPoint = currentPoint
			},

			touchEnd() {
				this.isDrawing = false
			},

			clearSignature() {
				this.canvasContext.clearRect(0, 0, 300, 200)
				this.canvasContext.draw()
			},

			saveSignature() {
				uni.canvasToTempFilePath({
					canvasId: 'signatureCanvas',
					success: (res) => {
						this.uploadImage(res.tempFilePath, 'signature')
						this.showSignatureModal = false
					}
				}, this)
			},

			toggleAgreement() {
				this.isAgreed = !this.isAgreed
			},

			viewAgreement() {
				// 跳转到协议页面
				uni.navigateTo({
					url: '/pages/identity/agreement'
				})
			},

			async submitForm() {
				// 表单验证
				if (!this.formData.region) {
					uni.showToast({
						title: '请选择运营地区',
						icon: 'none'
					})
					return
				}

				if (!this.formData.realname) {
					uni.showToast({
						title: '真实姓名不可为空',
						icon: 'none'
					})
					return
				}

				if (!this.formData.id_number) {
					uni.showToast({
						title: '身份证号码不可为空',
						icon: 'none'
					})
					return
				}

				if (!this.formData.idfromt) {
					uni.showToast({
						title: '请上传身份证正面照',
						icon: 'none'
					})
					return
				}

				if (!this.formData.idback) {
					uni.showToast({
						title: '请上传身份证背面照',
						icon: 'none'
					})
					return
				}

				if (!this.formData.workSpot) {
					uni.showToast({
						title: '请上传办公场地照片',
						icon: 'none'
					})
					return
				}

				if (!this.formData.teamP) {
					uni.showToast({
						title: '请上传团队照片',
						icon: 'none'
					})
					return
				}

				if (!this.formData.nameP) {
					uni.showToast({
						title: '请填写电子签名',
						icon: 'none'
					})
					return
				}

				if (!this.isAgreed) {
					uni.showToast({
						title: '请点击阅读同意优享优品平台市运营协议',
						icon: 'none'
					})
					return
				}

				// 提交表单
				uni.showLoading({
					title: '提交中...'
				})

				try {
					const submitData = {
						region: this.formData.region,
						realname: this.formData.realname,
						id_number: this.formData.id_number,
						cfi_path: this.formData.idfromt,
						cbi_path: this.formData.idback,
						st_path: this.formData.nameP,
						ws_path: this.formData.workSpot,
						tp_path: this.formData.teamP,
						created: new Date().getTime()
					}

					let res
					if (this.agentId) {
						// 修改信息
						submitData.agent_id = this.agentId
						res = await agentApi.updateAgentInfo(submitData)
					} else {
						// 新增申请
						res = await agentApi.addAgentInfo(submitData)
					}

					if (res.r === 0) {
						this.showSuccessModal = true
					} else {
						uni.showToast({
							title: res.msg || '提交失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('提交失败:', error)
					uni.showToast({
						title: '提交失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			confirmSuccess() {
				this.showSuccessModal = false
				uni.navigateTo({
					url: '/pages/identity/shenqing-more'
				})
			},

			goBack() {
				uni.navigateBack()
			},

			formatDate(timestamp) {
				const date = new Date(timestamp * 1000)
				return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.header {
		display: flex;
		align-items: center;
		height: 88rpx;
		background-color: #fff;
		border-bottom: 1px solid #eee;
		position: relative;

		.back-btn {
			position: absolute;
			left: 30rpx;
			width: 40rpx;
			height: 40rpx;

			.back-icon {
				width: 100%;
				height: 100%;
			}
		}

		.page-title {
			flex: 1;
			text-align: center;
			font-size: 36rpx;
			font-weight: 500;
		}
	}

	.form-wrapper {
		padding: 30rpx;
		background-color: #fff;
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1px solid #eee;

		.required {
			color: red;
			margin-right: 16rpx;
			font-size: 30rpx;
		}

		.label {
			width: 250rpx;
			font-size: 28rpx;
		}

		.input-field {
			// flex: 1;
			height: 60rpx;
			padding: 0 20rpx;
			background-color: #fff;
			border-radius: 8rpx;
			font-size: 28rpx;

			&.disabled {
				// background-color: #f5f5f5;
				color: #999;
			}
		}
	}

	.photo-section {
		margin-top: 40rpx;

		.section-title {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;

			.required {
				color: red;
				margin-right: 16rpx;
				font-size: 30rpx;
			}

			text {
				font-size: 28rpx;
			}
		}

		.photo-row {
			display: flex;
			gap: 30rpx;
			margin-left: 30rpx;
		}

		.photo-item {
			display: flex;
			flex-direction: column;
			align-items: center;

			.photo-img-idcard {
				width: 318rpx;
				height: 192rpx;
				border-radius: 8rpx;
			}

			.photo-img {
				width: 218rpx;
				height: 192rpx;
				border-radius: 8rpx;

				&.work-photo {
					width: 218rpx;
					height: 192rpx;
				}
				
			}
			.signature-img {
				height: 192rpx;
			}

			.photo-label {
				margin-top: 16rpx;
				font-size: 24rpx;
				color: #666;
			}
		}
	}

	.info-item {
		display: flex;
		align-items: center;
		padding: 30rpx 0;
		font-size: 28rpx;

		.date-text {
			color: #9f9f9f;
		}
	}

	.agreement-item {
		padding: 30rpx 0;
		.check-icon{
			width: 25rpx;
			height: 25rpx;
			margin-right: 5rpx;
		}

		.agreement-text {
			font-size: 28rpx;

			&.unread {
				color: #999;
			}

			
		}
		.agreement-link {
			color: #11b445;
			text-decoration: underline;
		}
	}

	.tip-text {
		display: block;
		margin: 30rpx 0;
		font-size: 24rpx;
		color: #ff2e00;
		text-align: center;
	}

	.submit-btn {
		width: 100%;
		height: 88rpx;
		background-color: #ff6b35;
		color: #fff;
		font-size: 34rpx;
		border-radius: 8rpx;
		border: none;
		margin-top: 40rpx;
	}

	.region-picker {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 500rpx;
		background-color: #fff;
		z-index: 1000;
	}

	.signature-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #fff;
		z-index: 1000;

		.signature-header {
			display: flex;
			align-items: center;
			height: 88rpx;
			border-bottom: 1px solid #eee;
			position: relative;

			.back-btn {
				position: absolute;
				left: 30rpx;
				width: 40rpx;
				height: 40rpx;

				.back-icon {
					width: 100%;
					height: 100%;
				}
			}

			.page-title {
				flex: 1;
				text-align: center;
				font-size: 36rpx;
				font-weight: 500;
			}
		}

		.signature-canvas {
			width: 100%;
			height: calc(100vh - 88rpx - 120rpx);
			background-color: #f9f9f9;
		}

		.signature-actions {
			display: flex;
			height: 120rpx;

			.action-btn {
				flex: 1;
				height: 100%;
				border: none;
				font-size: 32rpx;

				&.primary {
					background-color: #ff6b35;
					color: #fff;
				}
			}
		}
	}

	.success-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;

		.modal-content {
			width: 650rpx;
			max-height: 80vh;
			background-color: #fff;
			border-radius: 20rpx;
			padding: 60rpx;

			.success-title {
				font-size: 26rpx;
				color: #414141;
				margin-bottom: 30rpx;
			}

			.fee-info {
				display: flex;
				font-size: 24rpx;
				margin-bottom: 40rpx;

				.fee-left {
					width: 300rpx;

					.fee-label {
						margin-bottom: 14rpx;
					}

					.payment-method {
						font-size: 30rpx;
						color: red;
						margin: 14rpx 0;
					}
				}

				.fee-right {
					flex: 1;

					.fee-desc {
						margin-bottom: 34rpx;

						.amount {
							color: red;
						}
					}

					.qr-codes {
						display: flex;
						gap: 20rpx;
						margin-top: 20rpx;

						.qr-code {
							width: 100rpx;
							height: 119rpx;
						}
					}
				}
			}

			.confirm-btn {
				width: 100%;
				height: 80rpx;
				background-color: #ff6b35;
				color: #fff;
				font-size: 30rpx;
				border: none;
				border-radius: 8rpx;
			}
		}
	}
</style>